<?php
namespace app\faxing\channel;


use app\common\model\Gameulog;
use app\common\model\Order;
use app\common\model\Player;
use app\common\model\PlayerRole;
use app\index\controller\Exception;
use think\cache\driver\Redis;
use think\Db;
use think\facade\Log;
use think\facade\Session;
use app\common\controller\FaXingBase;

/**
 * 后台首页
 * Class Index
 * @package app\admin\controller
 */
class Qiqi extends FaXingBase
{

    public function register($params)
    {
        $cid = $params['cid'];
//        $sign_data = $params;
        $sign_data = [
            'qqesuid'=> '14545557',
            'channelid'=> 1,
            'channeluid'=> '10707989',
            'qqesnickname'=> '同阳曜',
            'qqesavatar'=> '',
            'cpgameid'=> '1642',
            'ext'=> '{"game":"hyjh5","appkey":"175575914978","token":"6ee8cc00badedb5c4ca7a84a15f1581c","channel":"0","is_realname":1,"is_adult":1,"age":42,"pay_method":1}',
            'qqestimestamp'=> '1761648662',
            'sign'=> 'a0e0697e86cd8e75b2db6170add7',

        ];
        unset($sign_data['cid']);
        unset($sign_data['gid']);
        unset($sign_data['qqesavatar']);
        $sign = $sign_data['sign'];
        unset($sign_data['sign']);
        $check_sign = $this->get_sign($sign_data);

//        if($check_sign != $sign){
//            $this->error("签名错误");
//        }


        $account = $cid."_".$params['qqesuid'];
        $player = Player::getOne(['account'=>$account]);
        if(!$player){
            //注册
            $data['account'] = $account;
            $data['password'] = get_encrypt('123456');
            $data['type'] = 0;
            $data['cid'] = $this->cid;
            $data['gid'] = $this->gid;
            try {
                Db::startTrans();
                $player = Player::register($data);
                Db::commit();
            }catch (Exception $e) {
                Db::rollback();
                $this->error("登录失败，请稍后再试。");
                Log::info("用户注册失败:".$e->getMessage());
            }
        }
        $game = $this->game;
        $data['uid'] = $player['id'];
        //记录登录信息
        Gameulog::addLog($data);
        $token = get_encrypt($data['uid']);
        $player['token'] = $token;
        unset($player['password']);
        Session::set('palyerinfo', json_encode($player));
        //redis 保存用户信息
        $redis = new Redis();
        $player['third_data'] = $params;
        $redis->set($token, $player);
        if (strpos($game['api_login_url'], '?') !== false) {
            $game_url = $game['api_login_url']."&token=".$token;
        } else {
            $game_url = $game['api_login_url']."?token=".$token;
        }
        return ['game_url'=>$game_url,'token'=>$token];
    }
    public function order($order)
    {
        $role = PlayerRole::where(['gid'=>$order['gid'],'uid'=>$order['uid'],'cid'=>$order['cid']])->find();
        $param = $this->request->param();
        $account = get_player($order['uid'],'account');
        $account = explode("_",$account);
        $sign = get_sign(['order_no'=>$order['order_no']],$this->extdata['Paykey']); // 回传验证
        $redis = new Redis();
        $player = $redis->get($param['token']);
        $third_data = $player['third_data'];


        $data = [
            'order'=>$order['order_no'],//订单号
            'cpgameid'=>$this->extdata['game_id'],// 渠道游戏id
            'qqesuid'=>$third_data['qqesuid'],// SDK用户id
            'channelid'=>$third_data['channelid'] ?? 0,// 渠道id
            'channeluid'=> third_data['channeluid'],// 渠道用户id
            'cpguid'=>'6996685021d1355f',// cp在平台的唯一id
            'goodsname'=>$order['goods_name'],//商品名称
            'fee'=>(float) $order['amount'],//金额 两位小数（元）
            'ext'=> third_data['ext'],// 玩家登录时回传的ext
            'timestamp'=> time(), // 时间戳 10 位
        ];

        $sign = $this->get_sign($data);
        $data['attach'] = get_sign(['order_no'=>$order['order_no']],$this->extdata['Paykey']);// 我方二次验证签名
        $data['sign'] = $sign; // 签名
        return $data;
    }

    public function check_order($params)
    {
        $order_no = $params['cp_order'];
        // 双重校验
        $order_sign = get_sign(['order_no'=>$order_no],$this->extdata['Paykey']);

        if($order_sign != $params['attach']){
            echo 'fail,sig error';exit;
        }

        // 查询订单
        $order = Order::where([
            'order_no'=>$order_no
        ])->find();

        if(!$this->check_sign($params)){
            echo 'fail,sig error';exit;
        }


        if($order['amount'] != $params['rmb']){
            echo json_encode(['status'=>-11,'message'=>'金额错误']);exit;
        }
        $order->trade_no = $params['orderid'];
        $order->save();

        return $order;
    }

    public function message($message,$order)
    {
        echo "success";exit;
    }

    protected function check_sign($params)
    {
        $sign = $params['sign'];
        unset($params['attach']);
        unset($params['sign']);
        $check_sign = $this->get_sign($params);
        if($check_sign != $sign){
            return false;
        }
        return true;
    }

    private function get_sign($data){
        ksort($data);
        $str = '';
        foreach ($data as $k => $v) {
            $str .= $k.'='.$v.'&';
        }
        $str = rtrim($str,'&');
        $strKey = $str.'&'.$this->extdata['Appkey'];

        $check_sign = md5($strKey);

        return $check_sign;
    }

}